import { useCallback, useEffect, useState } from 'react'
import { useLocation, useMatches, useNavigate, useOutlet } from 'react-router-dom'

function getKey() {
  return new Date().getTime().toString()
}

export function useTabs() {
  const { pathname, key } = useLocation()
  const matches = useMatches()
  const [tabs, setTabs] = useState<any[]>([])
  const [tabKey, setTabKey] = useState(pathname)
  const children = useOutlet()
  const navigate = useNavigate()

  useEffect(() => {
    const nowRoute = matches.at(-1)

    // 刷新页面时 路由会在动态创建之前匹配一次 此时是没有handle的
    // 路由每次切换key都会重新生成
    if (!nowRoute?.handle) return

    const tabItem = tabs.find((item) => item.key === (nowRoute?.handle as any)?.routePath)

    if (!tabItem) {
      // 这种写法拿到tabs的最新值
      setTabs((pre) => {
        const newTabs = pre.length === 8 ? [...pre.slice(1)] : [...pre]
        newTabs.push({
          label: (nowRoute?.handle as any)?.title,
          key: (nowRoute?.handle as any)?.routePath,
          childKey: getKey(),
          children
        })
        return newTabs
      })
    }

    setTabKey((nowRoute?.handle as any)?.routePath)
  }, [pathname, key])

  // 关闭当前tab
  const tabClose = useCallback(
    (key: string) => {
      const newTabs = tabs.filter((item) => item.key !== key)
      setTabs(newTabs)
      if (key === tabKey) navigate(newTabs[newTabs.length - 1].key)
    },
    [tabKey, tabs]
  )

  // 刷新当前tab
  const tabRefresh = useCallback(() => {
    const newTabs = tabs.map((item) => {
      if (item.key === pathname) {
        item.childKey = getKey()
      }
      return item
    })
    setTabs(newTabs)
  }, [tabKey, tabs])

  // 关闭其他tab
  const tabCloseOther = useCallback(() => {
    const newTabs = tabs.filter((item) => item.key === pathname)
    setTabs(newTabs)
  }, [tabKey, tabs])

  return {
    tabs,
    tabKey,
    tabClose,
    tabRefresh,
    tabCloseOther
  }
}
